package com.yan.project.service;

import com.yan.core.common.utils.DateUtils;
import com.yan.project.controller.EmailControllerFeignClient;
import com.yan.project.mapper.EmailCodeMapper;
import com.yan.project.pojo.EmailCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Random;

/**
 * @author WangYan
 * @description:
 * @date 2021/3/15 17:27
 */
@Slf4j
@Service
public class EmailCodeService {

    @Resource
    private EmailCodeMapper emailCodeMapper;

    @Autowired
    private EmailControllerFeignClient emailControllerFeignClient;

    public Boolean create(String email) {
        //查询未过期验证码
        String code = emailCodeMapper.queryValidCode(email);
        System.out.println("查询未过期验证码 code : " + code);
        if (StringUtils.isBlank(code)) {
            code = new Random().nextInt(999999) + "";
            //创建时间
            Date createTime = DateUtils.getDate();
            //过期时间 5分钟
            Date expireTime = DateUtils.addMinutes(createTime, 5);
            emailCodeMapper.save(new EmailCode(email, code, createTime, expireTime));
        }
        return emailControllerFeignClient.email(email, code);
    }

    /**
     * 校验验证码是否正确，0正确1错误2超时
     *
     * @Author WangYan
     * @Date 2021/3/26 13:42
     */
    public Integer validate(String email, String code) {
        String dbCode = emailCodeMapper.queryValidCode(email);
        if (StringUtils.isBlank(dbCode)) {
            return 1;
        }
        if (dbCode.equals(code)) {
            return 0;
        }
        return 1;
    }
}
